<script lang="ts" setup>
// 组件
import comIcon from '@/components/common/com-icon/com-icon.vue';
import comNavigation from '../common/com-navigationBar/com-navigation.vue';
// 登录API
import { postLoginByPasswordAPI, postLoginByLoginAPI, postLoginByCodeAPI } from '@/api/login';
// vue
import { ref } from 'vue';
import { useRouter } from 'vue-router'
// pinia
import { useUserStore } from '@/store/modules/user';
// vant
import { showToast } from 'vant';
import type { CodeType, User } from '@/types/user';
import type { AxiosResponse } from 'axios';
// 登录
const pattern: RegExp = /^1\d{10}$/
const mobile = ref<string>('');
const password = ref<string>('');
const code = ref<string>('')
// 获取到的验证码
const CodeNum = ref()
// 校验函数返回 true 表示校验通过，false 表示不通过
const validator = () => {
  if (pswLogin.value) {
    return /^.{8,24}$/.test(password.value)
  } else {
    return password.value.trim() !== ''
  }
}
const validator1 = () => {
  console.log(
    code.value, CodeNum.value
  );

  return code.value === CodeNum.value
}
const onFailed = () => {
  console.log('failed');
};
// 显示隐藏密码
let flag = ref<boolean>(true)
const displayPassword = (val: boolean) => {
  flag.value = val
}
// 是否同意条款
const checked = ref<boolean>(false)

type Data<T> = {
  code: number;
  message: string;
  data: T;
};
// 获取验证码
let codeBtn = ref<string>('获取验证码')
const getCode = async () => {
  if (codeBtn.value !== '获取验证码') return
  let time = 60
  let res: AxiosResponse<Data<CodeType>> = await postLoginByCodeAPI(mobile.value, 'login')
  if (res.data.code === 10000) {
    showToast({
      message: "验证码为：" + res.data.data.code
    })
    CodeNum.value = res.data.data.code
    setInterval(() => {
      time--
      codeBtn.value = time + 's'
      if (time <= 0) {
        codeBtn.value = '获取验证码'
      }
    }, 1000);
  }
}
// 登录
const router = useRouter()
const userStore = useUserStore()
const loginByPasswordData = async () => {
  if (!checked.value) return showToast({
    message: '请勾选我已同意'
  })
  if (!mobile.value && !password.value) return
  let res: AxiosResponse<Data<User>>
  if (pswLogin.value) {
    console.log('密码登录');
    res = await postLoginByPasswordAPI(mobile.value, password.value)
  } else {
    console.log('验证码登录');
    res = await postLoginByLoginAPI(mobile.value, code.value)
  }
  if (res?.data.code === 10000) {
    userStore.setUser(res.data.data)
    showToast({
      message: "登录成功"
    })
    setTimeout(() => {
      // 跳转页面
      router.push('/index')
    }, 500);
  }
}
const login = () => {
  loginByPasswordData()
}
// 修改登录方式
let pswLogin = ref(false)
const changeLogin = () => {
  pswLogin.value = !pswLogin.value
}

// 去注册
const goRegister = () => {
  router.push('/register')
}
// qq登录
const qqLogin = () => {
  // @ts-ignore
  window.location.href = QC.Login.insertButton._getPopupUrl({
    appId: '102015968',
    redirectURI: 'http://consult-patients.itheima.net/login/callback'
  })
}
</script>
<template>
  <!-- 登录盒子 -->
  <div class="login_Box">
    <!-- 导航栏 -->
    <comNavigation>
      <template v-slot:right>
        <div @click="goRegister" class="register">注册</div>
      </template>
    </comNavigation>
    <header>
      <h3>{{ pswLogin ? '密码登录' : '手机验证码登录' }}</h3>
    </header>
    <van-form @failed="onFailed">
      <van-cell-group inset>
        <!-- 手机号 -->
        <div class="item">
          <van-field class="ipt" v-model="mobile" name="pattern" placeholder="请输入手机号"
            :rules="[{ pattern, message: '请输入正确的手机号' }]" />
        </div>
        <!-- 密码 -->
        <div v-show="pswLogin" class="item">
          <van-field :type="flag ? 'password' : 'text'" class="ipt" v-model="password" name="validator"
            placeholder="请输入密码" :rules="[{ validator, message: '密码需要8-24个字符' }]" />
          <div class="password-icon">
            <comIcon @click="displayPassword(true)" v-show="!flag" name='icons-login-eye-on' />
            <comIcon @click="displayPassword(false)" v-show="flag" name='icons-login-eye-off' />
          </div>
        </div>
        <!-- 验证码 -->
        <div v-show="!pswLogin" class="item">
          <van-field class="ipt" v-model="code" name="validator" placeholder="请输入验证码"
            :rules="[{ validator: validator1, message: '请输入正确的验证码' }]" />
          <div v-show="!pswLogin" @click="getCode" class="codeBtn">
            {{ codeBtn }}
          </div>
        </div>
      </van-cell-group>
      <!-- 用户协议 -->
      <van-cell class="after">
        <div class="checked">
          <van-checkbox icon-size="15px" v-model="checked" checked-color="#16c2a3">我已同意<span class="green">用户协议</span>
          </van-checkbox>
          <a class="forgot" href="javascript:;">忘记密码？</a>
        </div>
      </van-cell>
      <!-- 登录按钮 -->
      <div class="buttonBox" style="margin: 16px;">
        <van-button @click="login" round block class="submit_button" native-type="submit">
          登&nbsp;录
        </van-button>
        <a v-show="!pswLogin" href="javascript:;" @click="changeLogin">
          密码登录
          <comIcon class="arrow" name="icons-user-arrow" />
        </a>
        <a v-show="pswLogin" href="javascript:;" @click="changeLogin">
          手机验证码登录
          &#10145;
          <comIcon class="arrow" name="icons-user-arrow" />
        </a>
      </div>
    </van-form>
    <!-- 第三方登录 -->
    <div class="other">
      <div class="font">
        第三方登录
      </div>
      <div class="other_login" @click="qqLogin">
        <img src="../../assets/qq.png" alt="" />
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.login_Box {
  width: 100%;
  height: 100%;

  .navigation_Bar {
    width: 100%;
    height: 46px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid rgb(248, 249, 249);


    .register {
      font-size: 15px;
      color: rgb(22, 194, 163);
      padding: 0 16px;
    }
  }

  header {
    display: flex;
    padding: 30px 30px 50px;
    align-items: end;
    justify-content: space-between;

    h3 {
      font-size: 24px;
      font-weight: 400;
      margin: 0;
    }
  }

  .item {
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f5f6f7;

    .password-icon {
      position: absolute;
      right: 20px;
      top: 20px;
      width: 18px;
      height: 18px;
    }

    .ipt {
      padding: 14px 16px;
    }

    .codeBtn {
      position: absolute;
      right: 8px;
      top: 18px;
      color: #16c2a3;
    }
  }

  .green {
    color: #16c2a3;
    margin: 0 5px
  }

  .forgot {
    color: #3c3e42;
  }

  .after::after {
    border: none;
  }

  .after {
    .checked {
      display: flex;
      justify-content: space-between;
      margin: 10px 16px 0;
    }
  }

  .buttonBox {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;

    .submit_button {
      width: 315px;
      background-color: #16c2a3;
      font-size: 16px;
      color: #fff;
    }

    a {
      color: #16c2a3;
      margin-top: 10px;

    }
  }

  .other {
    margin-top: 60px;
    padding: 0 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    .font {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      margin: 20px 0;
      color: #969799;
    }

    .font::before {
      content: "";
      background-color: #f6f7f8;
      display: block;
      flex: 1;
      box-sizing: border-box;
      height: 1px;
    }

    .font::after {
      content: "";
      display: block;
      flex: 1;
      box-sizing: border-box;
      background-color: #f6f7f8;
      height: 1px;
    }

    .other_login {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        width: 44px;
      }
    }
  }


}
</style>
